package p2p.logic.connection.communication.type;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import p2p.logic.connection.communication.AbstractCommunicationHandler;
import p2p.logic.connection.communication.Communication;
import p2p.logic.connection.communication.message.Message;

/**
 * 
 * Listen - Concrete Implementation Class responsible for
 * listening for incomming connections  
 *
 */
public class Listen extends Communication {
	
	public Listen(AbstractCommunicationHandler handler, int port) {
		super(handler);

		try {
			this.socket = new DatagramSocket(port);
		
		} catch (SocketException e) {
		
			e.printStackTrace();
		
		}
	}

	@Override
	public void start() {
		
		try {
			
			while(true){
				byte[] recieved = new byte[1024];
				
				DatagramPacket packet = new DatagramPacket(recieved, recieved.length);
				
				socket.receive(packet);
				
				Message m  = new Message(recieved);
				
				this.handler.handleReceivedMessage(m);
			}
		}catch (SocketException e){
		
		}catch (IOException e) {
			e.printStackTrace();
		} 
		

	}

}
